package com.way.filemanager;

import hwdroid.app.HWActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;

import org.swiftp.ServerControlActivity;
import org.swiftp.Util;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.widget.Toast;

import com.way.filemanager.fragment.CategoryFragment;
import com.way.filemanager.fragment.activity2frag_if;
import com.way.filemanager.navigation.MyFileManager;
import com.way.filemanager.navigation.MyFileManager.FileListener;
import com.way.filemanager.navigation.NavigationListFragmant;
import com.way.filemanager.navigation.NavigationListFragmant.Mode;
import com.way.filemanager.navigation.NavigationListFragmant.SelectMode;
import com.way.filemanager.online.FileListFragment;
import com.way.filemanager.util.CommonFunc;
import com.way.filemanager.util.CustomViewPager;
import com.way.filemanager.util.UnZipDialog;

public class FileManagerAppFrame extends HWActivity {

	private static final String TAG = "FileManagerAppFrame";

	private static final String KEY_TAB = "tab";
	  private static final String INSTANCESTATE_TAB = "tab_index";
	  public static int CATEGORY_TAB_INDEX = 0;
	CustomViewPager mViewPager;
	TabsAdapter mTabsAdapter;
	int mActiveFragmentId = 0;
	boolean mIsSearch;
	boolean isViewPagerCanScroll = true;
	private final ArrayList<Fragment> mFragmentList = new ArrayList<Fragment>();

	private final int CROSS_FRAGMENT_NULL = 0;
	private final int CROSS_FRAGMENT_ONLINE_COPY = 1;
	private final int CROSS_FRAGMENT_ONLINE_CUT = 2;
	private final int CROSS_FRAGMENT_LOCAL_COPY = 3;
	private final int CROSS_FRAGMENT_LOCAL_CUT = 4;
	private int mCrossFragmentStatus = CROSS_FRAGMENT_NULL;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setSwipeBackEnable(false);
		LayoutInflater mInflater = LayoutInflater.from(this);
		mViewPager = (CustomViewPager) mInflater.inflate(
				R.layout.appmain_frame, null);
		setActivityContentView(mViewPager);
		mViewPager.setOffscreenPageLimit(2);
		final ActionBar bar = getActionBar();

		bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		// bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
		bar.setDisplayShowTitleEnabled(false);
		bar.setDisplayShowHomeEnabled(false);
		bar.setDisplayShowCustomEnabled(false);

		mTabsAdapter = new TabsAdapter(this, mViewPager);

		// mIsSearch = Intent.ACTION_SEARCH.equals(getIntent().getAction());

		mTabsAdapter.addTab(bar.newTab().setText(R.string.CategoryBrowse),
				CategoryFragment.class, null);
		mTabsAdapter.addTab(bar.newTab().setText(R.string.AllFiles),
				NavigationListFragmant.class, null);
		// jinglong add for online file
		mTabsAdapter.addTab(bar.newTab().setText(R.string.OnlineFiles),
				FileListFragment.class, null);
		// liweiping add for ftp server
		mTabsAdapter.addTab(bar.newTab().setText(R.string.tab_remote),
				ServerControlActivity.class, null);
		mTabsAdapter.notifyDataSetChanged();
		

	}

	Runnable mFmResume = null;

	@Override
	protected void onResume() {
		super.onResume();
		final MyFileManager fm = MyFileManager.getFm();
		if (fm != null) {
			mFmResume = new Runnable() {
				public void run() {
					fm.onResume();
				}
			};
			mHandler.postDelayed(mFmResume, 500);
		}
		if (!checkMediaStatus()) {
			mHandler.postDelayed(new Runnable() {
				public void run() {
					toastSDCardBusy();
					finish();
				}
			}, 500);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		MyFileManager fm = MyFileManager.getFm();
		if (fm != null) {
			mHandler.removeCallbacks(mFmResume);
			fm.onPause();
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(KEY_TAB, getActionBar().getSelectedNavigationIndex());
	}

	@Override
	protected void onDestroy() {
		for (Fragment mFg : mFragmentList) {
			activity2frag_if m = (activity2frag_if) mFg;
			m.exit();
		}
		super.onDestroy();
	}

	public class TabsAdapter extends FragmentPagerAdapter implements
			ActionBar.TabListener, ViewPager.OnPageChangeListener {
		private final Context mContext;
		private final ActionBar mActionBar;
		private final ViewPager mViewPager;
		private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

		final class TabInfo {
			private final Class<?> clss;
			private final Bundle args;

			TabInfo(Class<?> _class, Bundle _args) {
				clss = _class;
				args = _args;
			}
		}

		public TabsAdapter(Activity activity, ViewPager pager) {
			super(activity.getFragmentManager());
			mContext = activity;
			mActionBar = activity.getActionBar();
			mViewPager = pager;
			mViewPager.setAdapter(this);
			mViewPager.setOnPageChangeListener(this);
		}

		public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
			TabInfo info = new TabInfo(clss, args);
			tab.setTag(info);
			tab.setTabListener(this);
			mTabs.add(info);
			mActionBar.addTab(tab);
			// notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return mTabs.size();
		}

		@Override
		public Fragment getItem(int position) {
			Fragment Fg;
			TabInfo info = mTabs.get(position);
			Fg = Fragment.instantiate(mContext, info.clss.getName(), info.args);
			// BugID:99830:fix FragmentList size is 0 bug after change language
			// mFragmentList.add(position, Fg);
			return Fg;
		}

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {
		}

		@Override
		public void onPageSelected(int position) {
			if (mActionBar.getNavigationMode() == ActionBar.NAVIGATION_MODE_TABS)
				mActionBar.setSelectedNavigationItem(position);
			mActiveFragmentId = position;
			if (mFragmentList != null) {
				Log.d(TAG, "onPageSelected position is " + position
						+ ",mFragmentList size is " + mFragmentList.size());
			}
			if (position == 2) {
				if (mFragmentList != null && mFragmentList.size() > 2) {
					// mViewPager.setCurrentItem(2);
					Fragment f = mFragmentList.get(2);
					if (f instanceof FileListFragment) {
						Log.e(TAG, "onPageSelected call judgeUpload ");
						((FileListFragment) f).judgeUpload();
					}
				}
			}
		}

		@Override
		public void onPageScrollStateChanged(int state) {
		}

		@Override
		public void onTabSelected(Tab tab, FragmentTransaction ft) {
			Object tag = tab.getTag();
			for (int i = 0; i < mTabs.size(); i++) {
				if (mTabs.get(i) == tag) {
					mViewPager.setCurrentItem(i);
				}
			}
		}

		@Override
		public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
			// TODO Auto-generated method stub

		}
	}

	// BugID:99830:fix FragmentList size is 0 bug after change language
	public void setFragmentMap(int pos, Fragment m) {
		if (mFragmentList != null) {
			mFragmentList.add(pos, m);
		}
	}

	long mExitBackTimeout = -1;

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (mFragmentList.size() <= mActiveFragmentId) {
			return super.onKeyUp(keyCode, event);
		}
		activity2frag_if frag = (activity2frag_if) mFragmentList
				.get(mActiveFragmentId);
		if (frag.fragOnKeyUp(keyCode, event)) {
			Log.v(TAG, "onKeyUp return true");
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			// // Retrieve if the exit status timeout has expired
			// long now = System.currentTimeMillis();
			// boolean timeout = (mExitBackTimeout == -1 || (now -
			// mExitBackTimeout) > RELEASE_EXIT_CHECK_TIMEOUT);
			// // Check if there no history and if the user was advised in the
			// last
			// // back action
			// if (timeout) {
			// // Communicate the user that the next time the application will
			// be
			// // closed
			// this.mExitBackTimeout = System.currentTimeMillis();
			// DialogHelper.showToast(this, R.string.msgs_push_again_to_exit,
			// Toast.LENGTH_SHORT);
			// return true;
			// }

		}
		return super.onKeyUp(keyCode, event);

	}

	public void SetCanViewPagerMove(Boolean isCan) {
		isViewPagerCanScroll = isCan;
		mViewPager.setScanScroll(isCan);
	}

	@Override
	public boolean onSearchRequested() {
		Log.v(TAG, "onSearchRequested");
		return true;
	}

	@Override
	protected void onNewIntent(Intent intent) {
		Log.d(TAG,
				"onNewIntent intent is " + intent + ",extra is "
						+ intent.getExtras() + ",action is "
						+ intent.getAction());
		// BugID:103938:clear flag of use mobile network
		if (intent != null) {
			if ("android.intent.action.MAIN".equals(intent.getAction())) {
				if (mFragmentList != null && mFragmentList.size() > 2) {
					Fragment f = mFragmentList.get(2);
					if (f instanceof FileListFragment) {
						((FileListFragment) f).setMobileFlag();
					}
				}
			}
		}
		if (intent != null && intent.getExtras() != null) {
			String isOnline = intent.getExtras().getString("isOnline");
			String path = intent.getExtras().getString("path");
			Log.e(TAG, "onNewIntent isOnline is " + isOnline + ",path is "
					+ path);
			if (!TextUtils.isEmpty(isOnline)) {
				if ("true".equals(isOnline)) {
					if (mFragmentList != null && mFragmentList.size() > 2) {
						mViewPager.setCurrentItem(2);
						Fragment f = mFragmentList.get(2);
						if (f instanceof FileListFragment) {
							((FileListFragment) f).setLoginStatus(true);
						}
					}
				}
			}
		}

	}

	private NavigationListFragmant getNavigationListFragmant() {
		if (mFragmentList != null && mFragmentList.size() > 2) {
			Fragment f = mFragmentList.get(1);
			if (f instanceof NavigationListFragmant) {
				return (NavigationListFragmant) f;
			}
		}
		return null;
	}

	private FileListFragment getOnlineListFragmant() {
		if (mFragmentList != null && mFragmentList.size() > 2) {
			Fragment f = mFragmentList.get(2);
			if (f instanceof FileListFragment) {
				return (FileListFragment) f;
			}
		}
		return null;
	}

	public LinkedList<File> getSelectedFiles() {
		NavigationListFragmant n = getNavigationListFragmant();
		return n != null ? n.getSelectedFiles() : null;
	}

	public void setSelectedMode(SelectMode from) {
		NavigationListFragmant n = getNavigationListFragmant();
		if (n != null) {
			if (mCrossFragmentStatus != CROSS_FRAGMENT_NULL) {
				n.setNormalMode(from);
				mCrossFragmentStatus = CROSS_FRAGMENT_NULL;
			}
		}

	}

	public void setOnlineSelectedMode() {
		FileListFragment n = getOnlineListFragmant();
		if (n != null) {
			if (mCrossFragmentStatus != CROSS_FRAGMENT_NULL) {
				n.StartTypeNormal();
				mCrossFragmentStatus = CROSS_FRAGMENT_NULL;
			}
		}

	}

	public void setCrossSelectedMode() {
		mCrossFragmentStatus = CROSS_FRAGMENT_LOCAL_COPY;
	}

	public SelectMode getSelectedMode() {
		SelectMode ret;
		NavigationListFragmant n = getNavigationListFragmant();
		if (n != null) {
			ret = n.getSelectedMode();
			return ret;
		}
		return SelectMode.share;
	}

	public boolean listLocalPath(FileListener l) {
		NavigationListFragmant n = getNavigationListFragmant();
		if (n != null) {
			mCrossFragmentStatus = CROSS_FRAGMENT_ONLINE_COPY;
			return n.listLocalPath(l);
		}
		return false;
	}

	LocalHandler mHandler = new LocalHandler();
	final int UnZipDialog_MSG_ID = 1;
	final String UnZipDialog_MSG_ID_KEY = "UnzipArg";

	@SuppressLint("HandlerLeak")
	class LocalHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			Log.v(TAG, "FileDeleteDialog msg.what:" + msg.what);
			switch (msg.what) {
			case UnZipDialog_MSG_ID:
				Bundle data = msg.getData();
				String[] lstPath = data.getStringArray(UnZipDialog_MSG_ID_KEY);
				UnZipDialog mUnZipDialog = new UnZipDialog(
						FileManagerAppFrame.this, lstPath[0], lstPath[1]);
				mUnZipDialog.show();
				break;
			default:
				break;
			}
		}
	}

	public class LocalFileListener implements FileListener {

		Mode mToStatus;
		SelectMode mFromStatus;
		String[] mfullpath;

		public LocalFileListener(Mode to, SelectMode from, String[] fullpath) {
			mToStatus = to;
			mFromStatus = from;
			mfullpath = fullpath;
		}

		@Override
		public void onFile(File file) {
			// TODO Auto-generated method stub
			Log.v(TAG, "mRootPath:" + file.getPath());
			if (mFromStatus == SelectMode.Unzip) {
				Message msg = mHandler.obtainMessage(UnZipDialog_MSG_ID);
				Bundle data = new Bundle();

				data.putStringArray(UnZipDialog_MSG_ID_KEY, new String[] {
						mfullpath[0], file.getAbsolutePath() });
				msg.setData(data);
				mHandler.sendMessage(msg);

			}
		}

	}

	public boolean listLocalPathPaste(FileListener l, Mode to, SelectMode from,
			String[] fullpath) {
		Log.v(TAG, "listLocalPathPaste:" + mFragmentList);
		Log.v(TAG, "listLocalPathPaste :" + mFragmentList.size());
		final LocalFileListener mLocalFileListener = new LocalFileListener(to,
				from, fullpath);
		if (mFragmentList != null && mFragmentList.size() >= 2) {
			Fragment f = mFragmentList.get(1);
			if (f instanceof NavigationListFragmant) {
				mViewPager.setCurrentItem(1);
				Log.v(TAG, "listLocalPathPaste setCurrentItem");
				if (l == null)
					((NavigationListFragmant) f).listLocalPathPaste(
							mLocalFileListener, to, from, fullpath);
				else
					((NavigationListFragmant) f).listLocalPathPaste(l, to,
							from, fullpath);
			}
		}

		return false;
	}

	private boolean checkMediaStatus() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_SHARED)
				|| status.equals(Environment.MEDIA_UNMOUNTED)) {
			return false;
		}
		return true;
	}

	boolean mIsSDBusyMsgShown = false;

	private void toastSDCardBusy() {
		if (!mIsSDBusyMsgShown) {// mIsFirstLevel &&
			Toast.makeText(this, R.string.sdcard_busy_message,
					Toast.LENGTH_SHORT).show();
			mIsSDBusyMsgShown = true;
		}
	}
}
